package cn.jdemo.juc.CountDownLatch;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @description
 * @date 2020/12/7
 */
public class DemoCountDownLatch01 {

    public static void main(String[] args) {
        test01();
    }

    /**
     * 执行结果如下:(countDownLatch类减到0才能执行完毕)
     * 开始监督...
     * 工作_10:...
     * 工作_9:...
     * 工作_7:...
     * 工作_8:...
     * 结束监督...
     * 工作_6:...
     */
    public static void test01() {
        CountDownLatch countDownLatch = new CountDownLatch(3);

        // ExecutorService 线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        });
        executorService.execute(()->{
            System.out.println("开始监督...");
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // countDownLatch 累减到0才会执行
            System.out.println("结束监督...");
        });

        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        AtomicInteger atomicInteger = new AtomicInteger(10);
        for (int i=0;i<3;i++){
            new Thread(()->{
                System.out.println("工作_"+atomicInteger.getAndDecrement()+":...");
                countDownLatch.countDown();
            }).start();
        }
    }
}
